#!/usr/bin/python
# -*- coding: utf-8 -*-

import subprocess
import sys
import os
import socket
import datetime

class CONFIG:
    PROCESSNUM = 2

class Monitor(object):
    def __init__(self, processName):
        self._processName = processName

    def _is_running(self):
        pids = []
        try:    
            p = subprocess.Popen(["ps","-C", self._processName, "-o", "pid"], stdout = subprocess.PIPE, close_fds = True)
            stdout = p.communicate()
        except Exception, e:
            print "error at %s, error:%s" %(__file__, str(e))
            return None
        if stdout and type(stdout) is tuple:
            pids = str(stdout).split("\\n")[1:-1]
            map(int, pids)
        
        return pids

    def run(self):
        _runningPids = self._is_running()
        _processNum = len(_runningPids)
        if _processNum != CONFIG.PROCESSNUM:
            self._term_process(_runningPids)
            self._start_process()

    def _start_process(self):
        os.system("nohup node /zhangbo/socketProxy/server/serverProxy.js &")
        os.system("nohup node /zhangbo/socketProxy/server/socketProxy.js &")

    def _term_process(self, pids):
        if not pids:
            pids = self._is_running(self._processName)
        if pids:
            for pid in pids:
                try:
                    os.kill(int(pid), signal.SIGTERM) 
                except OSError:
                    return None
            return 1

        else:
            return None

if __name__ == "__main__":
    if len(sys.argv) > 1:
        processName = sys.argv[1]

        M = Monitor(processName)
        M.run()
